<?php
class Helper_FwwebRequest{
	//入口 公有
	var $url;		//欲分析的url地址
	var $post;		//POST DATA
	var $auth = array('USER' => "tengfei ye","PWD"=>"jufei654");
	var $content;	//读取到的内容
	var $regExp;	//要获取部分的正则表达式

	var $codeFrom;	//原文的编码
	var $codeTo;	//欲转换的编码
	var $timeout;   //采集等待的时间

	var $startFlag;		//文章开始采集的标志 默认为0		在进行采集条目时，只对$startFlag 和 $endFlag之间的文字块进行搜索和采集。
	var $endFlag;		//文章结束采集的标志 默认为文章末尾	在进行采集条目时，只对$startFlag 和 $endFlag之间的文字块进行搜索和采集。 	
	var $block;			//$startFlag 和 $endFlag之间的文字块
	//出口	私有
	var $result;		//输出结果

	//初始化收集器
	function init(){
		if(empty($url))
		$this->getFile();
		$this->convertEncoding();
		$this->getBlock();
	}
	//采集所需内容
	function parse(){
		preg_match_all($this->regExp, $this->block ,$this->result,PREG_SET_ORDER);
		return $this->block;
	}
	//错误处理
	function error($msg){
		echo $msg;
	}
	//读取远程网页 如果成功，传回文件；如果失败传回false
    function getFile(){
    	
		$pars['POST']=$this->post;
		$pars['AUTH']=$this->auth;
    	$this->content = _fetchUrl($this->url,$pars);
     }
	 //获取所需要的文字块
	 function getBlock(){
	 	if( strpos($this->content,$this->startFlag)===false || strpos($this->content,$this->endFlag) ===false ){
	 		$this->block = "";
	 	}else{
	 		$this->block = $this->content;
			if(!empty($this->startFlag))
				$this->block = substr($this->block,strpos($this->block,$this->startFlag));
			if(!empty($this->endFlag))
				$this->block = substr($this->block,0,strpos($this->block,$this->endFlag));
	 	}
	 }
	 //内容编码的转换
	 function convertEncoding(){
		if(!empty($this->codeTo))
			$this->codeFrom = mb_detect_encoding($this->content);
		//如果给定转换方案，才执行转换。
		if(!empty($this->codeTo))
			$this->content = mb_convert_encoding($this->content,$this->codeTo,$this->codeFrom) or $this->error("can't convert Encoding");
	 }
	 
	 function parseTable($html = ""){	
		 
		$html == "" && 	$html = $this->block;

		$regExp = "|<TABLE(.*)</TABLE>|Uis";
		
		preg_match_all("|<TR(.*)</TR>|Uis", $html ,$tr_list,PREG_PATTERN_ORDER);
		$tr_list = $tr_list[0];
		foreach ($tr_list as &$tr){
			preg_match_all("|<TD(.*)</TD>|Uis", $tr ,$td_list,PREG_PATTERN_ORDER);
			$td_list = $td_list[0];
			
			
			foreach ($td_list as &$td){
				$td = trim(strip_tags($td));
			}
			$tr = $td_list;
		}
		return $tr_list;
	}
	static function parseHtml($html){
		$dom = Helper_HtmlDom::str_get_dom($html);
		$result = $dom->find("table tr");
		$i = 0;
		foreach ($result as $tr_nod){
			$td_list = $tr_nod->find("td");
			foreach ($td_list as $td_nod){
				$data[$i][] = strip_tags($td_nod->innertext);
			}
			$i++;
		}
		return $data;
	}	
	/**
	 * 获取lot信息
	 *
	 * @param string $lot_no
	 * @return array|int
	 * 
	 * 如果返回的是整数
	 * 
	 * 0 表示该lot是无效的LotNo
	 * -1:FW Server 连接出错
	 */
	static function getLotInfo($lot_no){
		static $_cache= array();
		if(null == $_cache[$lot_no]){
			$FW = new Helper_FwwebRequest();
			$FW->url = "http://fwwebtools.szs.st.com:8003/lotattribute/browfunc_bylot.php?lotfind=".$lot_no;
			$FW->init();
			$file_content = $FW->content;
			
			if(str_replace("Invalid Lot","",$file_content) != $file_content){
				$ret = 0;
			} else {

				$start_pos = strpos($file_content,'GetLotInfo(') + 11;
				$lot_info_json = substr($file_content,$start_pos,-1);
		
				$json = new Helper_JSON();
				$tmp_data = _json2array($json->decode($lot_info_json));
				
				$lot_info = array();
				
				foreach ($tmp_data as $property){
					$lot_info = array_merge($lot_info,$property);
				}
				
				//If the lot in different step(ASSY Or TESTING),we got different group
				$group = substr($lot_info[PROCESSGROUP],0,2);
				
				//In different group, we the values of some fields means different thing
				switch ($group){
					
					case "AG":
						$data['device'] 		=  $lot_info['PRODUCT'];
						$data['ag_processplan'] 	= $lot_info['PROCESSPLAN'];
						break;
						
					case "TG":
						$data['sales_type'] 	=  $lot_info['PRODUCT'];
						$data['device'] 		=  $lot_info['PRODUCTFROM'];
						$data['tg_processplan'] 	= $lot_info['PROCESSPLAN'];
						break;
				}
				
				
				//mapping the field name
				$data['lot_no'] 		= $lot_info['LOTID'];
				$data['lot_from'] 		= $lot_info['LOTFROM'];
				$data['diffusion_no'] 	= $lot_info['DIFFUSIONLOTNUMBER'];
				$data['process_plan'] 	= $lot_info['PROCESSPLAN'];
				$data['lot_type'] 		= $lot_info['LOTTYPE'];
				$data['quantity_in'] 	= $lot_info['CURRENTQTY'];
				$data['fw_quantity'] 	= $lot_info['CURRENTQTY'];
				$data['fw_step'] 		= $lot_info['CURRENTSTEP'];
				
				$data = _trimAll($data);
				
				$ret = ($data['lot_no'] == $lot_no) ? $data : -1; //服务器错误返回-1
			}
			$_cache[$lot_no] = $ret;
		}
		
		return $_cache[$lot_no];
	}
	
	static function getProductCodeInfo($product_code){
		$FW = new Helper_FwwebRequest();
		$FW->url = "http://fwwebtools.szs.st.com:8000/FwWeb/FwWeb0004_ProductConfig/browfunc.php?&prodfindget=".$product_code;
		$FW->startFlag = "<table width = '100%'> ";
		$FW->endFlag = "</HTML>";
		$FW->init();
		
		$FW->regExp = "|<td class='rptfont' width = '40%'>Plan \(Default\) </td>(.*)<a(.*)>(.*)ver|Uis";
		$FW->parse();
		
		$process_plan = trim(strip_tags($FW->result[0][3]));
		$FW->regExp = "|<td class='rptfont' width = '10%'>Product From    </td>  <td class='rptfont' width = '15%'>(.*)</td>|Uis";
		$FW->parse();
		
		$product_from = trim(strip_tags($FW->result[0][1]));
		
		$ret = $process_plan == "" ? array() : compact("process_plan","product_from");
		return $ret;
	}
	
	
	static function getLotHistory($lot_no){
		static $_cache= array();
		if(null == $_cache[$lot_no]){
			$C = new Helper_FwwebRequest();
			$C->url = "http://fwwebtools.szs.st.com:8000/FwWeb/FwWeb0001_LotQuery/browfunc.php?&lotfind={$lot_no}";
			$C->startFlag = "<table width = '100%' border='0'> <tr bgcolor = lightblue> <td class='rptfont' width= '2%'><b>Step";
			$C->endFlag   =	"<table width='100%'><tr><td class='rptfont' align='center'><b>*** End of report ***</b></td></tr></table>";
			$C->init();
			$body = $C->parseHtml($C->block);
			array_shift($body);
			array_pop($body);
			$_cache[$lot_no] = $body;
		}
		return $_cache[$lot_no];
	}
	
	static function getElotInfo($process_group){
		
		// Initiate an FW object
		$FW = new Helper_FwwebRequest();
		
		// Specify the url we want to read
		$FW->url = "http://fwwebtools.szs.st.com:8000/FwWeb/FwWeb0006_WIPSituation/browfunc.php";
		
		//Specify the form data we posted
		$FW->post="procgrp=$process_group&runrep=Run&selCombo=*&selcond=ALL&seldifflot=*&selexclotmode=*&selgroupcode=*&sellotmode=*&selmacropkg=*&selncl=*&selnumlotsv=N&selorder=Step-Prod&seloutputformat=CSV&selpackingtype=*&selpkg=*&selplanningfamily=*&selpnlcode=*&selprocessplan=*&selprocessspeed=*&selprocgrp=AG5&selprodmaturity=*&selproduct=*&selproductfrom=*&selshelfloc=*&selstatus=*&selstepgroupfrom=*&selstepgroupto=*&selstepname=*&selsummary=0&seltco=*&seltype=E&tempnumopts=0";
		
		$FW->startFlag = "Process Group";
		$FW->endFlag = "*** End of report ***";
		
		$FW->init();
		$result = $FW->block;
		
		if (strpos($result,"No data found") !== false) {
			return array();
		}
		
		$data = explode("\n",trim($result));
		array_shift($data);
		
		$records = array();
		foreach ($data as $key => $value){

			$value = explode(",",$value);
			$value = _trimAll($value);
			
			
			$lot_no 		= $value[5];
			$product_code 	= $value[4];
			$process_plan 	= $value[10];
			$current_step 	= $value[2];
			$hrs_at_step 	= $value[18];
			$due_date 		= date("Y-m-d",strtotime($value[17]));
			$current_qty 	= $value[8];
			$status		 	= $value[15];
			
			if (substr($process_plan,-4) == "SHIP" && substr($process_plan,0,2) == "AG") {
				$assy_only = 1;
			} else {
				$assy_only = 0;
			}
			if (substr($current_step,-7) == "RAWLINE" || substr($process_plan,0,2) != "AG") {
				$assy_completed = 1;
			} else {
				$assy_completed = 0;
			}
			if (substr($current_step,-7) == "RAWLINE" && substr($process_plan,-4) != "SHIP"){
				$ready_for_test = 1;
			}
			
			$location_vars = array(
				"lot_no","product_code","process_plan",
				"current_step","hrs_at_step","due_date",
				"current_qty","status","assy_only","assy_completed",
				"ready_for_test"
			);
			$records[] = compact($location_vars);
			
		}
		
		return $records;
		
	}
	
	static function getMidasData($prodlevel,$schedulercode,$lottype){
		$file_content = _fetchUrl("http://fwwebtools.szs.st.com:8003/Midasdata-IC/midasdata.php?prodlevel=TF&schedulercode=SZDP&lottype=P");
		$start_pos = strpos($file_content,'GetMidasData(') + 13;
		$lot_info_json = substr($file_content,$start_pos,-1);
		$json = new Helper_JSON();
		$tmp_data = _json2array($json->decode($lot_info_json));
		d($tmp_data);
	}
	/**
	 * 获取wip的信息
	 *
	 * @param string $process_group 多个process group用逗号隔开
	 * @param string $product
	 * @return array
	 */
	static function getWipInfo($process_group,$product="*"){
		$FW = new Helper_FwwebRequest();
		
		$FW->url = "http://fwwebtools.szs.st.com:8000/FwWeb/FwWeb0006_WIPSituation/browfunc.php";
		$FW->post = "procgrp={$process_group}&runrep=Run&selCombo=*&selcond=ALL&seldifflot=*&selexclotmode=*&selgroupcode=*&sellotmode=*&selmacropkg=*&selncl=*&selnumlotsv=Y&selorder=Step-Prod&seloutputformat=HTM&selpackingtype=*&selpkg=*&selplanningfamily=*&selpnlcode=*&selprocessplan=*&selprocessspeed=*&selprocgrp=*&selprodmaturity=*&selproduct={$product}&selproductfrom=*&selshelfloc=*&selstatus=*&selstepgroupfrom=*&selstepgroupto=*&selstepname=*&selsummary=2&seltco=*&seltype=*&tempnumopts=0";
		$FW->startFlag = "<table width = '100%'> <tr>  <td class='rptfont' width = ' 5%'>";
		$FW->endFlag = "<table width = '100%'> <tr>  <td class='rptfont' width = '25%'><b>Total for Area: </b>";
		$FW->init();
		
		$result = $FW->parseTable();
		$ret = array();
		foreach($result as $key => $content){
			if(intval($content[0]) != $content[0] || empty($content[0])){
				unset($result[$key]);
			}else {
				
				$fw_step = $content[1];
				$qty = str_replace(',','',$content[2]);
				
				$ret[$fw_step] = $qty;
				
			}
		}
		/*
		//get step map
		$model_step_map = new Model_StepMap();
		$step_map = $model_step_map->getMap();	
		
		foreach($result as $key => $content){
			if(intval($content[0]) != $content[0] || empty($content[0])){
				unset($result[$key]);
			}else {
				$step_info['id'] = $content[0];
				$step_info['fw_step'] = $content[1];
				$step_info['qty'] = str_replace(',','',$content[2]);
				$step_info['hold_qty'] = str_replace(',','',$content[3]);
				$step_info['lot_count'] = $content[4];
				$step_info['short_step'] = $step_map[$content[1]];
				$result[$key] = $step_info;
			}
		}
		*/
		return $ret;
	}
	
	function readCloseInfo($product, $process_group, $start_time, $end_time = ""){
		
		if($end_time == "") $end_time = date("Y-m-d H:i:s");
		
		$start_time = strtotime($start_time);
		$end_time = strtotime($end_time);
		
		$start_date =  date("Y/m/d",$start_time);//"2009/03/24";
		$start_time_h =  date("H",$start_time);//"21";
		$start_time_m =  date("i",$start_time);//"00";
		
		
		$end_date =  date("Y/m/d",$end_time);//"2009/03/24";
		$end_time_h =  date("H",$end_time);//"21";
		$end_time_m =  date("i",$end_time);//"00";
		
		$FW = new Helper_FwwebRequest();
		$FW->url = "http://fwwebtools.szs.st.com:8000/FwWeb/FwWeb0007_ClosedLots/browfunc.php";
		$FW->post = "ns_enddate=$end_date&ns_endhour=$end_time_h&ns_endmin=$end_time_m&ns_stdate=$start_date&ns_sthour=$start_time_h&ns_stmin=$start_time_m&procgrp=$process_group&runrep=Run&sel2li=*&selassemblysite=*&selautostatus=*&seldifflot=*&selgroupcode=*&selinddomain=*&sellottype=P,E,T&selmacropkg=*&selncl=*&seloutputformat=HTM&selpackingtype=*&selpkg=*&selplanningfamily=*&selpnlcode=*&selprocgrp=*&selproduct=$product&selproductfrom=*&selqanumber=*&selstockroom=*&selsummary=2&seltco=*&tempnumopts=0";
		$FW->startFlag = "<table width = '100%' border=0> <tr >	<td class='rptfont' width= '30%' align='right' >";
		$FW->endFlag = "</table>";
		$FW->init();

		$result = $FW->parseTable();
		
		$ret['process_stage'] = $result[0][0];
		$ret['closed_qty'] = str_replace(',','',$result[0][1]);
		$ret['closed_lots'] = $result[0][3];
		
		return $ret;
	}
	
	static function getHlotList($processgroup){
		
		$FW = new Helper_FwwebRequest();
		$FW->url = "http://fwwebtools.szs.st.com:8000/FwWeb/FwWeb0021_StationaryLots/browfunc.php";
		$FW->post = "runrep=Run&selcttype=Hrs%40Step&selexclotmode=*&sellotmode=*&selminhrs=0&seloutputformat=HTM&selpriority=YES&selprocgrp=$processgroup&selproduct=*&selproductfrom=*&selreporttype=Detailed&selsortby=Process%20Group%2C%20Plannerid%2C%20Step%20group&selstatus=Hold&selstepgroupfrom=*&selstepgroupto=*&selstepname=*&seltype=*&tempnumopts=0";
		$FW->startFlag = "<table width = '100%' cellpadding = '0' cellspacing = '0'>";
		$FW->endFlag = "</table>";
		$FW->init();
		$result = $FW->parseTable();
		
		$ret = array();
		
		foreach ($result as $item){
			$lot_no = $item[3];
			
			if(preg_match("/GK[A-Z0-9]{8}/i",$lot_no)){
				$info = array();
				$ret[$lot_no]['lot_no'] = $item[3];
				$ret[$lot_no]['hrs_step'] = $item[2];
				$ret[$lot_no]['other'] = serialize($item);
			}
		}
		
		//当没有找到数据时确认FW正常返回了信息
		if (empty($ret)) {
			$is_find = strpos($FW->content,"No data found for selected options.");
			if($is_find === false){
				return false;
			}
		}
		return $ret;
	}
	
	
}//end of class